package com.canbot.u05.activity.agenda

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.canbot.u05.R
import com.canbot.u05.activity.agenda.bean.AgendaBean
import com.canbot.u05.activity.agenda.bean.AgendaPosBean
import com.canbot.u05.activity.agenda.bean.AgendaTypeBean
import com.canbot.u05.activity.agenda.bean.AgendaWorkDayBean
import com.canbot.u05.activity.agenda.calendar.*
import com.canbot.u05.activity.agenda.dao.AgendaDataTable
import com.canbot.u05.activity.agenda.dialog.TimeDialog
import com.canbot.u05.activity.agenda.dialog.TimeOneDialog
import com.canbot.u05.activity.agenda.dialog.TipDialog
import com.canbot.u05.activity.presidemode.newcode.BaseHostActivity
import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil
import com.canbot.u05.activity.presidemode.newcode.interfaces.IResponse
import com.canbot.u05.activity.presidemode.newcode.view.NHostBaseDialog
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import kotlinx.android.synthetic.main.activity_agenda_create.*
import java.util.*

/**
 * @author yinxiaowei
 * @date 2019/5/31
 */
class AgendaCreateActivity : BaseHostActivity(), View.OnClickListener {
    private val TAG = AgendaCreateActivity::class.java.simpleName
    private var mAgendaBean = AgendaBean()
    private var agendaDataTable: AgendaDataTable? = null // 如果是更新，这个不为空
    private val voicesCreate = arrayOf(arrayOf("${PathConst.AGENDA_VOICE_DIR}rwsz_gzrc_u05_001.mp3", "12"),
            arrayOf("${PathConst.AGENDA_VOICE_DIR}rwsz_gzrc_u05_002.mp3", "30"))
    private val voicesConfig = arrayOf(arrayOf("${PathConst.AGENDA_VOICE_DIR}rwct_gzrc_u05_001.mp3", "27"),
            arrayOf("${PathConst.AGENDA_VOICE_DIR}rwct_gzrc_u05_002.mp3", "13"))

    override fun initEventData() {
        agendaDataTable = intent.getSerializableExtra(DATA) as AgendaDataTable?
        agendaDataTable?.apply {
            mAgendaBean = this.agendaBean
            initView()
        }
        tv_save.setOnClickListener(this)
        agenda_type.setOnClickListener(this)
        agenda_time.setOnClickListener(this)
        work_day.setOnClickListener(this)
        agenda_pos.setOnClickListener(this)
        agenda_permission.setOnClickListener(this)

        playRandomVoiceWithEmotion(voicesCreate)
    }

    private fun initView() {
        switchItemTitle(mAgendaBean.agendaType)
        updateAgendaType(mAgendaBean.agendaType)
        updateTimeView(mAgendaBean.startTime!!, mAgendaBean.endTime)
        work_day.updateText(getDateNoYearStr(mAgendaBean.workDay))
        mAgendaBean.pos?.name?.let {
            agenda_pos.updateText(it)
        }
        updatePermissionView(mAgendaBean.pwd)
    }

    private fun updateAgendaType(agendaTypeBean: AgendaTypeBean) {
        when (agendaTypeBean.type) {
            getString(R.string.module_name_spbf), getString(R.string.module_name_wdby),
            getString(R.string.module_name_ypbf), getString(R.string.module_name_cxlk) -> {
                if (agendaTypeBean.data.isNotEmpty()) {
                    val stringBuilder = StringBuilder()
                    agendaTypeBean.data.forEach {
                        stringBuilder.append("${it.name},")
                    }
                    var data = stringBuilder.toString()
                    data = data.substring(0, data.length - 1)
                    agenda_type.updateText(data)
                } else {
                    agenda_type.updateText(getString(R.string.choice_none))
                }
            }
            getString(R.string.module_name_ybjd), getString(R.string.module_name_kqdk),
            getString(R.string.module_name_gbyd), getString(R.string.module_name_hbxc),
            getString(R.string.shutdown) -> {
                agenda_type.updateText(agendaTypeBean.type)
            }
        }

    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_agenda_create
    }

    fun back(view: View?) {
        val tipDialog = TipDialog(this, getString(R.string.exitTip_agenda))
        tipDialog.setiDialogBtnLisenter {
            exit(false)
        }
        tipDialog.show()
    }

    private fun exit(boolean: Boolean) {
        if (!boolean) { // 如果是保存退出的，不进行返回数据
            mAgendaBean = AgendaBean()
        }
        val intent = Intent()
        intent.putExtra(BaseHostActivity.DATA, mAgendaBean)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun onBackPressed() {
        exit(false)
    }

    /**
     * 保存按钮的点击事件
     */
    fun save() {
        val result = dataIsFull(mAgendaBean)
        if (TextUtils.isEmpty(result)) {
            val timeInValid = isTimeInValid(mAgendaBean)
            if (timeInValid) {
                ToastTools.newInstance(this).showText(getString(R.string.time_gone))
            } else {
                if (AgendaHomeActivity.agendaTableList.size > 0) {
                    val exist = isExistTimeTask(AgendaHomeActivity.agendaTableList, mAgendaBean)
                    if (exist != null) {
                        showConfligDialog(exist)
                    } else {
                        showSaveDialog(null)
                    }
                } else {
                    showSaveDialog(null)
                }
            }
        } else {
            ToastTools.newInstance(this).showText(result)
        }
    }


    private fun showConfligDialog(exist: AgendaDataTable) {
        val tipDialog = TipDialog(this, String.format(getString(R.string.agenda_time_common), exist.agendaBean.agendaType.type,
                String.format("%s - %s", getTime(exist.agendaBean.startTime), getTime(exist.agendaBean.endTime))))
        tipDialog.setiDialogBtnLisenter {
            showSaveDialog(exist)
        }
        tipDialog.show()
        playRandomVoiceWithEmotion(voicesConfig)
    }

    /**
     * 添加数据 / 更新数据
     */
    private fun showSaveDialog(exist: AgendaDataTable?) {
        showLoadingDialog(getString(R.string.data_upload))
        if (agendaDataTable != null) {
            agendaDataTable?.agendaBean = mAgendaBean
            NetLoadUtil.updateAgendaTask(this, object : IResponse<String> {
                override fun onSucusse(result: String?) {
                    dismissDialog()
                    exit(true)
                    ToastTools.newInstance(baseContext).showText(getString(R.string.upload_complete))
                }

                override fun onFailuer(result: String?) {
                    dismissDialog()
                    ToastTools.newInstance(baseContext).showText(result)
                }
            }, agendaDataTable, exist)
        } else {
            NetLoadUtil.addAgendaTask(this, object : IResponse<String> {
                override fun onSucusse(result: String?) {
                    dismissDialog()
                    exit(true)
                }

                override fun onFailuer(result: String?) {
                    dismissDialog()
                    ToastTools.newInstance(baseContext).showText(result)
                }
            }, mAgendaBean, exist)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_CTEATE_TYPE -> {
                val agendaTypeBean: AgendaTypeBean = data?.getSerializableExtra(DATA) as AgendaTypeBean
                updateAgendaType(agendaTypeBean)
                mAgendaBean.agendaType = agendaTypeBean
                switchItemTitle(agendaTypeBean)
            }
            REQUEST_PERMISSION -> {
                val pwd = data?.getBooleanExtra(DATA, false)!!
                mAgendaBean.pwd = pwd
                updatePermissionView(pwd)
            }
            REQUEST_WORK_POS -> {
                val agendaPosBean: AgendaPosBean? = data?.getSerializableExtra(DATA) as AgendaPosBean?
                agendaPosBean?.let {
                    mAgendaBean.pos = it
                    agenda_pos.updateText(it.name)
                }
            }
            REQUEST_WORK_DAY -> {
                val agendaWorkDayBean: AgendaWorkDayBean = data?.getSerializableExtra(DATA) as AgendaWorkDayBean
                mAgendaBean.workDay = agendaWorkDayBean
                val dateNoYearStr = getDateNoYearStr(agendaWorkDayBean)
                work_day.updateText(if (dateNoYearStr.isNotEmpty()) dateNoYearStr else getString(R.string.choice_none))
            }
        }
    }

    /**
     * 更新权限View
     */
    private fun updatePermissionView(pwd: Boolean) {
        if (!pwd) {
            agenda_permission.updateText(getString(R.string.no_permission))
        } else {
            agenda_permission.updateText(getString(R.string.yes_permission))
        }
    }

    private fun switchItemTitle(agendaTypeBean: AgendaTypeBean) {
        if (getString(R.string.shutdown) == agendaTypeBean.type) {
            showShutDownUI()
        } else {
            showNormalUI()
        }
    }

    /**
     * 工作议程 - 关机UI
     */
    private fun showShutDownUI() {
        agenda_time.updateTitle(getString(R.string.shutdown_time))
        agenda_time.updateText(getString(R.string.choice_none))
        work_day.updateTitle(getString(R.string.shutdown_date))
        work_day.updateText(getString(R.string.choice_none))
        agenda_pos.updateTitle(getString(R.string.shutdown_pos))
        agenda_permission.visibility = View.GONE
    }

    /**
     * 工作议程 - 正常UI
     */
    private fun showNormalUI() {
        agenda_time.updateTitle(getString(R.string.agenda_item_time))
        work_day.updateTitle(getString(R.string.agenda_item_work_day))
        agenda_pos.updateTitle(getString(R.string.agenda_item_work_pos))
        agenda_permission.visibility = View.VISIBLE
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_save -> {
                save()
            }
            R.id.agenda_type -> {
                val intent = Intent()
                intent.setClass(this, AgendaTypeActivity::class.java)
                intent.putExtra(DATA, mAgendaBean.agendaType)
                gotoActivityForResult(intent, REQUEST_CTEATE_TYPE)
            }
            R.id.agenda_time -> {
                if (getString(R.string.shutdown) == mAgendaBean.agendaType.type) {
                    showTimeSelectDialog(false)
                } else {
                    showTimeSelectDialog(true)
                }
            }
            R.id.work_day -> {
                val intent = Intent()
                intent.setClass(this, AgendaWorkDayActivity::class.java)
                intent.putExtra(DATA, mAgendaBean.workDay)
                gotoActivityForResult(intent, REQUEST_WORK_DAY)
            }
            R.id.agenda_pos -> {
                val intent = Intent()
                intent.setClass(this, AgendaWorkPosActivity::class.java)
                intent.putExtra(DATA, mAgendaBean.pos)
                gotoActivityForResult(intent, REQUEST_WORK_POS)
            }
            R.id.agenda_permission -> {
                val intent = Intent()
                intent.setClass(this, AgendaPermissionSetActivity::class.java)
                intent.putExtra(DATA, mAgendaBean.pwd)
                gotoActivityForResult(intent, REQUEST_PERMISSION)
            }
        }
    }

    private fun showTimeSelectDialog(isMultiSelect: Boolean) {
        val dialog: NHostBaseDialog = if (isMultiSelect) {
            TimeDialog(this, mAgendaBean.startTime, mAgendaBean.endTime)
        } else {
            TimeOneDialog(this, mAgendaBean.startTime)
        }
        dialog.setiDialogBtnLisenter {
            val list: ArrayList<Calendar> = it as ArrayList<Calendar>
            val startTime = list[0]
            mAgendaBean.startTime = startTime.timeInMillis
            mAgendaBean.startTime?.let { time ->
                if (isMultiSelect) {
                    mAgendaBean.endTime = list[1].timeInMillis
                    updateTimeView(time, mAgendaBean.endTime)
                } else {
                    mAgendaBean.endTime = time + 2 * 1000 // 如果是关机，结束时间模拟增加2s,  不显示
                    updateTimeView(time, null)
                }
            }
        }
        dialog.show()
    }

    private fun updateTimeView(startTime: Long, endTime: Long?) {
        if (endTime == null) {
            agenda_time.updateText(getTime(startTime))
        } else {
            agenda_time.updateText("${getTime(startTime)} - ${getTime(endTime)}")
        }
    }
}
